package org.sam.swing.table.editor;

import java.awt.BorderLayout;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.swing.JButton;

import org.sam.swing.JSDialog;
import org.sam.swing.annotation.Id;

/**
 * 集合数据编辑控件
 * 
 * @author sam
 *
 */
public class JSTableCollectionDialog<T> extends JSDialog {

	private static final long serialVersionUID = 4917356413023571811L;

	/**
	 * 多选主窗口
	 */
	@Id("selectPanel")
	private JSTableCollectionSelectPanel<T> selectPanel;

	/**
	 * 多选功能对话框
	 */
	public JSTableCollectionDialog(Collection<T> values) {
		this.initCompent(values, null);
	}

	/**
	 * 增加editor的操作
	 * 
	 * @param values
	 * @param cellEdit
	 */
	public JSTableCollectionDialog(Collection<T> values, T defaultValue) {
		this.initCompent(values, defaultValue);
	}

	/**
	 * 初始化控件
	 */
	protected void initCompent(Collection<T> values, T defaultValue) {
		this.setLayout(new BorderLayout());
		selectPanel = new JSTableCollectionSelectPanel<T>(values, defaultValue);
		this.add(selectPanel, BorderLayout.CENTER);
	}

	/**
	 * 打开窗口,并返回数据的操作
	 * @param values
	 * @return
	 */
	public static <T> Collection<T> openDialog(Collection<T> values, T defaultValue) {
		JSTableCollectionDialog<T> dialog = new JSTableCollectionDialog<>(values, defaultValue);
		AtomicBoolean ibOk = new AtomicBoolean(false);

		dialog.setLocationRelativeTo(null);
		dialog.setModal(true);
		dialog.setSize(320, 480);

		JButton btnOk = (JButton) dialog.selectPanel.findViewById("btnOk");
		btnOk.addActionListener(e -> {
			ibOk.set(true);
			dialog.setVisible(false);
		});

		JButton btnCancel = (JButton) dialog.selectPanel.findViewById("btnCancel");
		btnCancel.addActionListener(e -> {
			ibOk.set(false);
			dialog.setVisible(false);
		});
		dialog.setVisible(true);

		return ibOk.get() ? dialog.selectPanel.getValue() : null;
	}
}
